package cn.psvmc.cxzapi.exception;

import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.response.ResultGenerator;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 项目异常处理类:
 * 项目中所有controller层抛出的异常信息都会被拦截。
 * 方便我们查看异常原因，减少开发中大量的try catch。
 * 拦截异常后，打印异常信息，返回前端约定参数对象。
 */
@Slf4j
@ResponseBody
@ControllerAdvice
public class ErrorAdivceController {
    @ExceptionHandler(ServiceException.class)
    public Result missingParametersException(ServiceException ex) {
        log.error("提示信息:   -------> " + ex.getMessage());
        return ResultGenerator.genFailResult(ex.getMessage());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result DataIntegrityViolationException(DataIntegrityViolationException ex){
        log.error("数据库异常:   -------> " + ex.getMessage());
        String msg = ex.getMessage();
        if (ToolUtils.isNotEmpty(msg) && msg.contains("SQLIntegrityConstraintViolationException")){
            return ResultGenerator.genFailResult("存在关联信息");
        }
        return ResultGenerator.genFailResult("数据库处理异常：" + ex.getMessage());

    }


    /*
     * @Description exception异常，如果排查不出问题，注释该方法
     * @Date 2023/10/25 10:24:27
     * @Author WN
     * @Param [ex]
     * @Return cn.psvmc.cxzapi.vo.ResultVo
     **/
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception ex) {
        String msg = ex.getMessage();
        log.error("程序运行异常:   -------> " + msg);
        if (ToolUtils.isNotEmpty(msg) && msg.contains("JSON parse error")){
            return ResultGenerator.genFailResult("json格式不对");
        } else if (ToolUtils.isNotEmpty(msg) && (msg.contains("bad SQL")
                || msg.contains("java.sql.SQLException"))) {
            return ResultGenerator.genFailResult(msg);
        }
        return ResultGenerator.genFailResult("程序处理异常：" + msg);
    }

    @ExceptionHandler(NullPointerException.class)
    public Result nullPointerException(NullPointerException ex) {
        StackTraceElement element = ex.getStackTrace()[0];
        String msg = JSON.toJSONString(element);
        log.error("参数为空异常:   -------> " + msg);
        return ResultGenerator.genFailResult("参数为空异常：" + msg);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalArgumentExceptionHandler(HttpServletRequest request,IllegalArgumentException ex) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        if(parameterMap.isEmpty()){
            log.error("请求参数错误 URL : {}，Exception : {}", request.getRequestURL(),"请求参数为空");
        }else{
            log.error("请求参数错误 URL : {}，Exception : {}", request.getRequestURL(),ex.getMessage());
        }

        return ResultGenerator.genFailResult("请求参数错误 :" + ex.getMessage());
    }


}
